import { Button } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { history, getDvaApp } from 'umi';
import ProTable from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { useRef, useEffect, useState } from 'react';
import moment from 'moment';
import $utils from '@/utils/utils';
import { reportExportList } from '@/services/delivery';
type GithubIssueItem = {
  id: number;
  name: string;
  createTime: string;
};

const initDate = {
  startTime: moment().subtract(7, 'days').startOf('day'), //  开始时间
  endTime: moment().endOf('day'), // 结束时间
};

const Download: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  // 解决无法调用dispatch
  const dispatch = getDvaApp()._store.dispatch;

  const [initParams, setParams] = useState<any>();
  const [current, setCurrent] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(20);
  const [total, setTotal] = useState<number>(0);
  const l_state: any = history.location.state;

  useEffect(() => {
    $utils.addTab(dispatch, {
      name: '报表下载',
      path: '/BasicConfig/Download',
      isTopMenu: true,
      state: {},
    });
    if (!initParams) {
      const startTime = l_state?.startTime ? moment(l_state.startTime) : initDate.startTime;
      const endTime = l_state?.endTime ? moment(l_state.endTime) : initDate.endTime;
      setParams({
        name: l_state?.name || undefined,
        dateTime: [startTime, endTime],
      });
    }
  }, []);

  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '生成时间',
      dataIndex: 'dateTime',
      hideInTable: true,
      valueType: 'dateTimeRange',
      order: 8,
      colSize: 1.5,
      search: {
        transform: (value: any) => ({ startTime: value[0], endTime: value[1] }),
      },
      fieldProps: {
        disabledDate: (current: any) => {
          // 只可选择90天内，上线日期后
          return !(
            current > moment('06-14-2022', 'MM-DD-YYYY').endOf('days') &&
            current > moment().subtract(90, 'days') &&
            current < moment().subtract(0, 'days').endOf('days')
          );
        },
        ranges: {
          今天: [moment().startOf('day'), moment().endOf('day')],
          昨天: [
            moment().subtract(1, 'days').startOf('day'),
            moment().subtract(1, 'days').endOf('day'),
          ],
          // 本周: [moment().startOf('week'), moment().endOf('week')],
          // 本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
            moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
          ],
        },
      },
    },
    {
      title: '报表名称',
      dataIndex: 'name',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入报表名称',
      },
    },
    {
      title: '报表名称',
      dataIndex: 'name',
      search: false,
    },
    {
      title: '生成时间',
      dataIndex: 'createTime',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text: any, record: any) => (
        <Button type="link" onClick={() => $utils.onExport(record)}>
          下载
        </Button>
      ),
    },
  ];

  return (
    <PageContainer>
      {initParams && (
        <ProTable<GithubIssueItem>
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          rowKey="id"
          form={{
            initialValues: initParams,
          }}
          search={{
            span: 6,
            optionRender: (searchConfig, formProps, dom) => [
              dom.reverse()[0],
              <Button
                key="resetText"
                onClick={() => {
                  formRef?.current?.setFieldsValue({
                    dateTime: [initDate.startTime, initDate.endTime],
                    name: undefined,
                  });
                }}
              >
                重置
              </Button>,
            ],
          }}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          pagination={{
            pageSize: pageSize,
            showSizeChanger: true,
            size: 'small',
            total: total,
            onShowSizeChange: (current, pageSize) => {
              setCurrent(current);
              setPageSize(pageSize);
            },
          }}
          onSubmit={() => {}}
          request={async (data) => {
            const params = {
              current,
              pageSize,
              name: data.name || '',
              startTime: data?.startTime || '',
              endTime: data?.endTime || '',
            };
            const msg = await reportExportList(params);
            $utils.addTab(dispatch, {
              name: '报表下载',
              path: '/BasicConfig/Download',
              isTopMenu: true,
              state: params,
            });
            setParams(params);
            setTotal(msg.body?.count);
            return {
              data: msg.body?.list || [],
              success: msg.code === 0,
            };
          }}
        />
      )}
    </PageContainer>
  );
};

export default Download;
